package com.syncomponents.support;

import java.io.IOException;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.util.Assert;

/**
 * 请求资源, 需要配置jaxb class bound, refresh 方法用于解析xml成ResourceBean
 * 
 * @author sunkey
 * @date Jan 16, 2014
 */
public abstract class AbstractXMLRequestResource<T extends ResourceBean> extends ApplicationObjectSupport implements
        IRequestResource {

    protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractXMLRequestResource.class);

    /**
     * 客户端服务资源集合
     */
    private Map<String, T> resourceMap;

    public AbstractXMLRequestResource() {
        refresh();
    }

    /**
     * 解析xmlPath为对象
     * 
     * @param xmlPath classpath下文件路径
     * @param classesToBeBound xml绑定的对象
     */
    private void register(String xmlPath, Class<?>... classesToBeBound) {
        Assert.notNull(xmlPath);
        Assert.notNull(classesToBeBound);
        try {
            LOGGER.info("psrse {},classesToBeBound: {}", xmlPath, classesToBeBound);
            Object object = XMLParser.parse(xmlPath, classesToBeBound);
            resourceMap = XMLParser.convertToResources(object);
            Assert.notNull(resourceMap);
        } catch (JAXBException e) {
            logger.error("jaxb unmarshal failure", e);
        } catch (IOException e) {
            logger.error("jaxb unmarshal failure", e);
        }
    }

    public void refresh() {
        register(getResource(), getClazz());
    }

    public abstract Class<?>[] getClazz();

    public abstract String getResource();

    @SuppressWarnings({ "hiding", "unchecked" })
    @Override
    public <T extends ResourceBean> T getResource(String action) {
        Object obj = resourceMap.get(action);
        Assert.notNull(obj, "request resource wasn’t found");
        return (T) obj;
    }

}
